/**
 * 
 */
package com.zznode.client.wlanpolling.other;

import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.zznode.client.wlanpolling.EnumRunMode;
import com.zznode.client.wlanpolling.R;
import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.WLanContext;
import com.zznode.client.wlanpolling.model.LoadDataFromNetworkCompleted;
import com.zznode.client.wlanpolling.model.NeighbouringAPManager;
import com.zznode.client.wlanpolling.utils.WLanPollingUtils;

/**
 * @author Pink
 * 
 */
public class NeighbouringAPListTabActivity extends TabActivity implements
		LocationListener, LoadDataFromNetworkCompleted {
	public static final String TAB_1 = "1miles";
	public static final String TAB_5 = "5miles";
	public static final String TAB_10 = "10miles";

	private WLANPollingApplication application;

	private double lontitue = 0, latitude = 0;
	private LocationManager locationManager = null;
	private String bestProvider = null;

	private ProgressDialog pBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.neighbouringtab);

		application = (WLANPollingApplication) getApplication();

		NeighbouringAPManager.setContext(application.getContext());
		NeighbouringAPManager.getNeighbouringAPManager().registListener(this);
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		bestProvider = locationManager.getBestProvider(criteria, false);

		pBar = new ProgressDialog(this);
		pBar.setTitle("正在初始化定位服务");
		pBar.setMessage("请稍候...");
		pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pBar.show();
		
		Location location = locationManager.getLastKnownLocation(bestProvider);
		WLanContext context = application.getContext();
		if((location != null && ((int)location.getLongitude()) != 0) || 
				(context.getApLatitude() != null && context.getApLongtitude() != null)) {
			if (WLanPollingUtils.RUN_MODE == EnumRunMode.DEBUG) {
				this.lontitue = WLanPollingUtils.DEBUG_LONTITUE;
				this.latitude = WLanPollingUtils.DEBUG_LATITUDE;
			} else {
				if(location != null) {
					this.lontitue = location.getLongitude();
					this.latitude = location.getLatitude();
				} else {
					try {
						this.lontitue = Float.parseFloat(context.getApLongtitude());
						this.latitude = Float.parseFloat(context.getApLatitude());
					} catch(NumberFormatException exp){}
				}
			}
			pBar.setTitle("正在获取当前位置信息");
			NeighbouringAPManager.getNeighbouringAPManager().loadDataFromNetwork(
					lontitue, latitude);
		} else {
			pBar.cancel();
			pBar = null;
			Toast.makeText(this, "无法获取当前位置,请保证定位服务器已经开启!", Toast.LENGTH_LONG).show();
			initTab();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		NeighbouringAPManager.getNeighbouringAPManager().unRegistListener(this);
		locationManager.removeUpdates(this);
	}

	private void addTab(String label, String tag, Class<?> c) {
		TabHost tabHost = getTabHost();
		Intent intent = new Intent(this, c);
		intent.putExtra("tag", tag);
		TabHost.TabSpec spec = tabHost.newTabSpec(tag);

		View tabIndicator = LayoutInflater.from(this).inflate(
				R.layout.tab_indicator, getTabWidget(), false);
		ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
		icon.setVisibility(View.GONE);
		TextView title = (TextView) tabIndicator.findViewById(R.id.title);
		title.setText(label);

		spec.setIndicator(tabIndicator);
		spec.setContent(intent);

		if (tag.equals(TAB_1)) {
			tabIndicator.setBackgroundResource(R.drawable.menu_activebg02);
		} else {
			tabIndicator.setBackgroundResource(0);
		}

		tabHost.addTab(spec);
	}

	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(bestProvider, 10*000, 20, this);
	}
	
	@Override
	public void onLocationChanged(Location location) {
		if (WLanPollingUtils.RUN_MODE == EnumRunMode.DEBUG) {
			this.lontitue = WLanPollingUtils.DEBUG_LONTITUE;
			this.latitude = WLanPollingUtils.DEBUG_LATITUDE;
		} else {
			this.lontitue = location.getLongitude();
			this.latitude = location.getLatitude();
		}
		//位置改变后，重新Load数据
		//NeighbouringAPManager.getNeighbouringAPManager().loadDataFromNetwork(
		//		lontitue, latitude);
	}

	@Override
	public void onProviderDisabled(String provider) {
		//Toast.makeText(this, "定位服务器已经关闭!", Toast.LENGTH_LONG).show();
		//initTab();
	}

	@Override
	public void onProviderEnabled(String provider) {
		//Toast.makeText(this, "定位服务器已经开启!", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		if(status == LocationProvider.OUT_OF_SERVICE || status == LocationProvider.TEMPORARILY_UNAVAILABLE) {
			Toast.makeText(this, "无法获取当前位置的经纬度信息,请确认GPS是否打开!", Toast.LENGTH_LONG).show();
			initTab();
		}
	}
	
	private void closeProgressDialog() {
		if(pBar != null) {
			pBar.cancel();
			pBar = null;
		}
	}
	
	private void initTab() {
		TabHost tabHost = getTabHost();
		tabHost.clearAllTabs();

		addTab("1公里内", TAB_1, NeighbouringAPListActivity.class);
		addTab("5公里内", TAB_5, NeighbouringAPListActivity.class);
		addTab("10公里内", TAB_10, NeighbouringAPListActivity.class);

		tabHost.setCurrentTab(0);
		
		getTabHost().setOnTabChangedListener(new TabHost.OnTabChangeListener() {

			@Override
			public void onTabChanged(String tabId) {
				for (int i = 0; i < 3; i++) {
					View view = getTabHost().getTabWidget().getChildTabViewAt(i);
					if(view == null)
						return;
					view.setBackgroundResource(0);
					
					/*
					if (view != getTabHost().getCurrentTabView()) {
						((ImageView) view.findViewById(R.id.icon))
								.setImageResource(tabInactiveRes[i]);
					} else {
						((ImageView) view.findViewById(R.id.icon))
								.setImageResource(tabActiveRes[i]);
					}
					*/
				}
				
				getTabHost().getCurrentTabView().setBackgroundResource(
						R.drawable.menu_activebg02);
			}
		});
		closeProgressDialog();	
	}

	@Override
	public void onCompleted(Exception exp) {

		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				initTab();
			}
		});
	}
}
